package com.itheima.filter;

import com.alibaba.fastjson.JSON;
import com.itheima.common.MyThreadLocal;
import com.itheima.common.R;
import lombok.extern.slf4j.Slf4j;
import org.springframework.util.AntPathMatcher;

import javax.servlet.*;
import javax.servlet.annotation.WebFilter;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import java.io.IOException;

@WebFilter("/*")
@Slf4j
public class LoginFilter implements Filter {

    public static final AntPathMatcher PATH_MATCHER= new AntPathMatcher();

    @Override
    public void doFilter(ServletRequest servletRequest, ServletResponse servletResponse, FilterChain filterChain) throws IOException, ServletException {
        HttpServletRequest request = (HttpServletRequest) servletRequest;
        HttpServletResponse response = (HttpServletResponse) servletResponse;

        //获取请求路径
        String uri = request.getRequestURI();
        //定义放行的路径数组
        String [] urls = new String[]{
                "/employee/login",
                "/backend/**",
                "/front/**",
               "/common/**",
                "/user/sendMsg",
                "/user/login",
                "/doc.html",
                "/webjars/**",
                "/swagger-resources",
                "/v2/api-docs"
        };
        //判断请求路径是否不需要登录就可以访问
        //借助工具类
        for (String url : urls) {
            boolean match = PATH_MATCHER.match(url, uri);
            if (match){
                //放行
                filterChain.doFilter(request,response);
                return;
            }
        }
        //判断是否已经登陆
        HttpSession session = request.getSession();
        Object employee = session.getAttribute("employee");
        if (employee != null){
            //放行
            Long id = (Long) session.getAttribute("employee");
            MyThreadLocal.setCurrentId(id);
            filterChain.doFilter(request,response);
            return;
        }
        //判断用户是否已经登陆
        Object user = session.getAttribute("user");
        if (user != null){
            //放行
            Long userId = (Long) session.getAttribute("user");
            MyThreadLocal.setCurrentId(userId);
            filterChain.doFilter(request,response);
            return;
        }
        log.info("未登录");
        response.getWriter().write(JSON.toJSONString(R.error("NOTLOGIN")));
    }
}
